package cn.qingyun.gis.modules.baogan.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.baogan.entity.MicroStreetAuditLog;
import cn.qingyun.gis.modules.baogan.entity.MicroStreetData;
import cn.qingyun.gis.modules.baogan.entity.MicrogridCareRecordEntity;
import cn.qingyun.gis.modules.baogan.enums.*;
import cn.qingyun.gis.modules.baogan.mapper.PoiScenarioAdminMapper;
import cn.qingyun.gis.modules.baogan.service.IPoiScenarioAdminService;
import cn.qingyun.gis.modules.baogan.service.MicroStreetDataService;
import cn.qingyun.gis.modules.baogan.service.MicrogridCareRecordService;
import cn.qingyun.gis.modules.baogan.vo.PoiScenarioLikeRequest;
import cn.qingyun.gis.modules.baogan.vo.request.*;
import cn.qingyun.gis.modules.baogan.vo.response.DataResponse;
import cn.qingyun.gis.modules.baogan.vo.response.MicroGridBaseInfoVo;
import cn.qingyun.gis.modules.baogan.vo.response.ScenePersonAndTeamVo;
import cn.qingyun.gis.modules.baogan.vo.response.StreetDataRes;
import cn.qingyun.gis.modules.init.system.vo.LoginUser;
import cn.qingyun.gis.modules.init.utils.SystemUtil;
import cn.qingyun.gis.modules.scenes.contant.ScenesStatus;
import cn.qingyun.gis.modules.scenes.contant.ReviewEnum;
import cn.qingyun.gis.modules.scenes.entity.PoiScenario;
import cn.qingyun.gis.modules.scenes.entity.UniAddrRegion;
import cn.qingyun.gis.modules.scenes.mapper.PoiScenarioMapper;
import cn.qingyun.gis.modules.scenes.service.IPoiScenarioService;
import cn.qingyun.gis.modules.scenes.service.IUniAddrRegionService;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author guest
 * @since 2024-04-27
 */
@Slf4j
@Service
@DS("scenes_offensive")
public class PoiScenarioAdminServiceImpl extends ServiceImpl<PoiScenarioMapper, PoiScenario> implements IPoiScenarioAdminService {

    @Resource
    private IUniAddrRegionService uniAddrRegionService;
    @Resource
    private MicroStreetDataService microStreetDataService;
    @Resource
    private MicrogridCareRecordService microStreetRecordService;

    @Resource
    private PoiScenarioAdminMapper poiScenarioAdminMapper;

    @Resource
    private IPoiScenarioService poiScenarioService;
    @Resource
    private MicroStreetAuditLogService microStreetAuditLogService;
    @Resource
    private MicrogridCareRecordService microgridCareRecordService;

    @Override
    public List<PoiScenario> selectPoiDateByName(PoiScenarioLikeRequest request) {
        log.debug("管理后台模糊搜索接口入参{}", request);
        List<String> types = request.getTypes();
        if (types.contains(ScenesStatus.BUSINESS.getDesc())) {
            types.add(ScenesStatus.COMPLEX.getDesc());
        }
        //1.根据编码查询区划中心点
        QueryWrapper<UniAddrRegion> wrapper = new QueryWrapper<>();
        wrapper.select("level", "name", "code", "ST_X(center_point) AS lon", "ST_Y(center_point) AS lat")
                .eq("code", request.getCode())
                .ne("state", -1);
        UniAddrRegion uniAddrRegion = uniAddrRegionService.getBaseMapper().selectOne(wrapper);
        if (uniAddrRegion == null || uniAddrRegion.getLon() == null || uniAddrRegion.getLat() == null) {
            throw new CommonException("查询区划中心点错误");
        }
        request.setLon(uniAddrRegion.getLon());
        request.setLat(uniAddrRegion.getLat());
        //2.查询区划等级
        Integer level = uniAddrRegionService.selectLevel(request.getCode());
        request.setLevel(level);
        //3.模糊搜索
        List<PoiScenario> list = poiScenarioAdminMapper.selectPoiDataByName(request);
        //处理商业综合体类型-->变为商务楼宇
        list.forEach(poiScenario -> {
            if (poiScenario.getType().equals(ScenesStatus.COMPLEX.getDesc())) {
                poiScenario.setType(ScenesStatus.BUSINESS.getDesc());
            }
        });
        log.debug("模糊搜索结果返回{}", list);
        return list;
    }

    @Override
    public List<DataResponse> selectPoiAndPolygonData(DataQueryRequest request) {
        log.debug("点面数据查询入参{}", request);
        BigDecimal rtLon = request.getRtLon();
        BigDecimal rtLat = request.getRtLat();
        BigDecimal lbLon = request.getLbLon();
        BigDecimal lbLat = request.getLbLat();
        List<String> types = request.getTypes();
        if (types.contains(ScenesStatus.BUSINESS.getDesc())) {
            types.add(ScenesStatus.COMPLEX.getDesc());
        }
        Integer level = uniAddrRegionService.selectLevel(request.getCode());
        QueryWrapper<UniAddrRegion> regionWrapper = new QueryWrapper<>();
        regionWrapper.select("id", "name as micro_grid_name", "level", "wkt", "ST_AsText(center_point) AS centerPoint", "code as micro_grid_code").eq("code", request.getCode()).ne("state", -1);
        UniAddrRegion uniAddrRegion = uniAddrRegionService.getBaseMapper().selectOne(regionWrapper);
        if (uniAddrRegion == null || StringUtils.isEmpty(uniAddrRegion.getWkt().toText())) {
            throw new CommonException("未查询到该码的面数据！");
        }
        //1.基础数据查询
        CompletableFuture<List<DataResponse>> missionOne = CompletableFuture.supplyAsync(() ->
                        poiScenarioService.selectPoiData(request, level))
                .exceptionally(e -> {
                    log.error("基础数据查询报错: {},{}", e.getMessage(), e);
                    throw new CommonException("基础数据查询报错");
                });
        //2.路网+自己画的面+圈画
        CompletableFuture<List<DataResponse>> missionTwo = CompletableFuture.supplyAsync(() -> {
            List<DataResponse> list = Lists.newArrayList();
//            QueryWrapper<MicroStreetData> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("id", "name", "ST_AsText(wkt) AS wkt", "ST_X(ST_Centroid(wkt)) as lng", "ST_Y(ST_Centroid(wkt)) as lat", "type", "protract_flag", "micro_grid_code", "micro_grid_name")
//                    .apply(String.format("ST_Intersects(ST_SetSRID(wkt,4326),ST_GeomFromText('MULTIPOLYGON(((%s %s,%s %s,%s %s,%s %s,%s %s)))',4326))",
//                            lbLon, lbLat, lbLon, rtLat, rtLon, rtLat, rtLon, lbLat, lbLon, lbLat))
//                    .apply(String.format("ST_Intersects(ST_SetSRID(wkt,4326),ST_GeomFromText('%s',4326))", uniAddrRegion.getWkt().toText()))
//                    .in("type", types);
//            List<MicroStreetData> microStreetData = microStreetDataService.getBaseMapper().selectList(queryWrapper);
            List<StreetDataRes> microStreetData = microStreetDataService.selectDateList(rtLon,rtLat,lbLon,lbLat,uniAddrRegion.getWkt().toText(),types);
            microStreetData.forEach(microStreet -> {
                DataResponse dataResponse = new DataResponse();
                BeanUtils.copyProperties(microStreet, dataResponse);
                dataResponse.setWkt(microStreet.getWkt());
                list.add(dataResponse);
            });
            return list;
        }).exceptionally(e -> {
            log.error("路网+自己画的面+圈画: {},{}", e.getMessage(), e);
            throw new CommonException("面数据查询报错");
        });
        CompletableFuture<List<DataResponse>> lastTotalData = CompletableFuture.allOf(missionOne, missionTwo).thenApply(v -> {
            List<DataResponse> list = Lists.newArrayList();
            List<DataResponse> oneList = missionOne.join();
            List<DataResponse> twoList = missionTwo.join();
            if (CollectionUtils.isNotEmpty(oneList)) {
                //处理商业综合体类型-->变为商务楼宇
                list.forEach(data -> {
                    if (data.getType().equals(ScenesStatus.COMPLEX.getDesc())) {
                        data.setType(ScenesStatus.BUSINESS.getDesc());
                    }
                });
                list.addAll(oneList);
            }
            if (CollectionUtils.isNotEmpty(twoList)) {
                list.addAll(twoList);
            }
            return list;
        }).exceptionally(e -> {
            log.error("数据查询报错: {},{}", e.getMessage(), e);
            throw new CommonException("点面数据查询报错");
        });
        List<DataResponse> list = Lists.newArrayList();
        try {
            list = lastTotalData.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.debug("点面数据查询集合大小{}", list.size());
        return list;
    }

    @Override
    public List<DataResponse> selectPoiAndPolygonMicroData(MicroDataRequest request) {
        log.debug("查询具体微网格下的点面数据入参{}", request);
        String code = request.getMicroGridCode();
        List<String> types = request.getTypes();
        if (types.contains(ScenesStatus.BUSINESS.getDesc())) {
            types.add(ScenesStatus.COMPLEX.getDesc());
        }
        QueryWrapper<UniAddrRegion> regionWrapper = new QueryWrapper<>();
        regionWrapper.select("id", "name", "level", "wkt", "ST_AsText(center_point) AS centerPoint").eq("code", code).ne("state", -1);
        UniAddrRegion uniAddrRegion = uniAddrRegionService.getBaseMapper().selectOne(regionWrapper);
        if (uniAddrRegion == null || StringUtils.isEmpty(uniAddrRegion.getWkt().toText())) {
            throw new CommonException("未查询到该码的面数据！");
        }
        //找到该网格的对应地市码
        QueryWrapper<UniAddrRegion> regionCityWrapper = new QueryWrapper<>();
        regionCityWrapper.select("id", "code", "name", "level", "wkt", "ST_AsText(center_point) AS centerPoint").eq("level", 2).ne("state", -1).apply(String.format("st_within(ST_GeomFromText('%s',4326),wkt)", uniAddrRegion.getWkt().toText()));
        UniAddrRegion uniAddrCityRegion = uniAddrRegionService.getBaseMapper().selectOne(regionCityWrapper);
        String regionCityCode = null;
        if (uniAddrCityRegion != null) {
            regionCityCode = uniAddrCityRegion.getCode();
        }
        String finalRegionCityCode = regionCityCode;
        //1.基础数据查询
        CompletableFuture<List<DataResponse>> missionOne = CompletableFuture.supplyAsync(() -> poiScenarioService.selectPoiDataByMicroCode(code, finalRegionCityCode, types)).exceptionally(e -> {
            log.error("微网格下基础数据查询报错: {},{}", e.getMessage(), e);
            throw new CommonException("微网格下基础数据查询报错");
        });
        //2.路网+自己画的面+圈画
        CompletableFuture<List<DataResponse>> missionTwo = CompletableFuture.supplyAsync(() ->
                microStreetDataService.selectDataResponse(request,uniAddrRegion.getWkt().toText())
        ).exceptionally(e -> {
            log.error("微网格下：路网+自己画的面+圈画: {},{}", e.getMessage(), e);
            throw new CommonException("微网格下面数据查询报错");
        });

        CompletableFuture<List<DataResponse>> lastTotalData = CompletableFuture.allOf(missionOne, missionTwo).thenApply(v -> {
            List<DataResponse> list = Lists.newArrayList();
            List<DataResponse> oneList = missionOne.join();
            List<DataResponse> twoList = missionTwo.join();
            if (CollectionUtils.isNotEmpty(oneList)) {
                //处理商业综合体类型-->变为商务楼宇
                oneList.forEach(data -> {
                    if (data.getType().equals(ScenesStatus.COMPLEX.getDesc())) {
                        data.setType(ScenesStatus.BUSINESS.getDesc());
                    }
                });
                list.addAll(oneList);
            }
            if (CollectionUtils.isNotEmpty(twoList)) {
                list.addAll(twoList);
            }
            return list;
        }).exceptionally(e -> {
            log.error("微网格下数据查询报错: {},{}", e.getMessage(), e);
            throw new CommonException("微网格下点面数据查询报错");
        });
        List<DataResponse> list = Lists.newArrayList();
        try {
            list = lastTotalData.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.debug("点面数据查询集合大小{}", list.size());
        return list;
    }

    /**
     * 查询微网格看管划分基本信息
     *
     * @param request
     * @return
     */
    @Override
    public MicroGridBaseInfoVo selectMicroGridBaseInfo(MicroGridCodeRequest request) {
        MicroGridBaseInfoVo microGridBaseInfoVo = new MicroGridBaseInfoVo();
        LambdaQueryWrapper<PoiScenario> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(PoiScenario::getMicroGridCode, request.getCode())
                .eq(PoiScenario::getIsBuild, 1);
        int buildCount = this.count(queryWrapper);
        microGridBaseInfoVo.setBuildCount(buildCount);
        queryWrapper.clear();
        queryWrapper
                .eq(PoiScenario::getMicroGridCode, request.getCode())
                .eq(PoiScenario::getIsBuild, 0);
        int companyCount = this.count(queryWrapper);
        microGridBaseInfoVo.setCompanyCount(companyCount);
        //查询场景及所选自有人员、团队列表
        if (CollectionUtils.isNotEmpty(request.getSceneTypeList())) {
            List<ScenePersonAndTeamVo> scenePersonAndTeamVos = microStreetRecordService.listScenePersonAndTeamVo(request);
            microGridBaseInfoVo.setScenePersonAndTeamVos(scenePersonAndTeamVos);
        }
        return microGridBaseInfoVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBoundary(PolygonRequest request) {
        log.info("管理后台添加边界入参{}", request);
        LoginUser currentUser = SystemUtil.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CommonException("解析用户失败");
        }
        //String type = request.getTypes().get(0);
        Integer protractFlag = request.getProtractFlag();
        Integer careFlag = request.getCareFlag();
        Assert.isTrue(ObjectUtil.isNotEmpty(careFlag), "参数校验失败----看管划分标识不能为空!");
        //根据微网格查询网格、区县、地市编码
        int startLevel = 5; // 起始级别
        int endLevel = 2;   // 结束级别
        List<UniAddrRegion> ancestors = uniAddrRegionService.getAncestorsUpToLevel(request.getMicroGridCode(), startLevel, endLevel);
        UniAddrRegion microRegion = ancestors.get(0);//微网格和网格
        UniAddrRegion gridRegion = ancestors.get(1);//网格和区县
        UniAddrRegion disRegion = ancestors.get(2);//区县和地市
        List<String> types = request.getTypes();
        List<Integer> sceneTypeList = types.stream().map(item -> {
            return SceneTypeEnum.getCodeByDesc(item);
        }).collect(Collectors.toList());

        for (String type : types) {
            MicroStreetData data = MicroStreetData.builder()
                    .id(UUID.randomUUID().toString())
                    .name(request.getName())
                    .wkt(request.getWkt())
                    .type(type)
                    .createTime(new Date())
                    .phone(currentUser.getPhone())
                    .createBy(currentUser.getUsername())
                    .workNo(currentUser.getWorkNo())
                    .protractFlag(protractFlag)
                    .cityCode(disRegion.getParentCode())
                    .cityName(disRegion.getParentName())
                    .disCode(gridRegion.getParentCode())
                    .disName(gridRegion.getParentName())
                    .gridCode(gridRegion.getCode())
                    .gridName(gridRegion.getName())
                    .microGridCode(request.getMicroGridCode())
                    .microGridName(request.getMicroGridName())
                    .build();
            if (careFlag == 1) {//判断是否看管
                data.setAssignState(AssignStateEnum.ASSIGNED.getCode());
            } else {
                data.setAssignState(AssignStateEnum.UNASSIGNED.getCode());
            }
            if (Objects.equals(protractFlag, ProtractEnum.DRAW.getCode())) {
                //绘制的面-----去查询父级，落到圈中
                MicroStreetData parent = microStreetDataService.selectParentByWkt(request.getWkt());
                if (Objects.nonNull(parent)) {
                    data.setParentId(parent.getId());
                }
            }
            microStreetDataService.saveBoundary(data);
            //是否需要更新父级Id
            if (Objects.equals(protractFlag, ProtractEnum.CIRCLE.getCode())) {
                //查询哪些点在这里面，然后更新parentId
                List<String> pointIds = microStreetDataService.selectPointInPolygon(data.getWkt());
                if (CollectionUtils.isNotEmpty(pointIds)) {
                    //如果有面落在圈画中，则更新parentId
                    microStreetDataService.updateParentIdById(pointIds, data.getId());
                }
            }

            //判断是否需要审核
            if (protractFlag.equals(ProtractEnum.DRAW.getCode()) && type.equals(SceneTypeEnum.STREET_SHOP.getDesc())) {//需要审核
                MicroStreetAuditLog record = MicroStreetAuditLog.builder()
                        .id(UUID.randomUUID().toString())
                        .streetId(data.getId())
                        .operationType(OperationTypeEnum.UPDATE.getCode())
                        .createBy(currentUser.getRealname())
                        .createPhone(currentUser.getPhone())
                        .createTime(new Date())
                        .createId(currentUser.getWorkNo())
                        .reviewState(ReviewEnum.REVIEWED.getCode())
                        .newWkt(request.getWkt())
                        .microGridCode(request.getMicroGridCode())
                        .microGridName(request.getMicroGridName())
                        .name(request.getName())
                        .build();
                microStreetAuditLogService.addAuditLog(record);
            }
            if (careFlag == 1) {
                //给面划分看管人
                if (CareTypeEnum.TEAM_DIRECT_SALE_PERSON.getCode().equals(request.getCareType())) {
                    //分配给团队人员
                    Assert.isTrue(CollectionUtils.isNotEmpty(request.getTeamNumberRequestList()), "团队人员不能为空");
                    //先删除待看管面中的已看管的点数据
                    microgridCareRecordService.deleteCareInfoInWkt(request.getWkt(), sceneTypeList);
                    request.getTeamNumberRequestList().forEach(item -> {
                        MicrogridCareRecordEntity microgridCareRecordEntity = new MicrogridCareRecordEntity();
                        BeanUtils.copyProperties(request, microgridCareRecordEntity);
                        microgridCareRecordEntity.setSceneType(SceneTypeEnum.getCodeByDesc(type));
                        microgridCareRecordEntity.setCaregiver(item.getCaregiver());
                        microgridCareRecordEntity.setStaffWorkNo(item.getStaffWorkNo());
                        microgridCareRecordEntity.setCreateBy(currentUser.getId());
                        microgridCareRecordEntity.setCreateTime(DateUtil.date());
                        microgridCareRecordEntity.setUpdateBy(currentUser.getId());
                        microgridCareRecordEntity.setUpdateTime(DateUtil.date());
                        microgridCareRecordEntity.setCareObject(protractFlag);
                        microgridCareRecordService.save(microgridCareRecordEntity);
                    });
                } else {
                    //分配给渠道
                    Assert.isTrue(StringUtil.isNotEmpty(request.getChannelCode()) || StringUtil.isNotEmpty(request.getChannelName()),
                            "渠道编码、渠道名称-不能为空");
                    //先删除待看管面中的已看管的点数据
                    microgridCareRecordService.deleteCareInfoInWkt(request.getWkt(), sceneTypeList);
                    MicrogridCareRecordEntity microgridCareRecordEntity = new MicrogridCareRecordEntity();
                    BeanUtils.copyProperties(request, microgridCareRecordEntity);
                    microgridCareRecordEntity.setSceneType(SceneTypeEnum.getCodeByDesc(type));
                    microgridCareRecordEntity.setCreateBy(currentUser.getId());
                    microgridCareRecordEntity.setCreateTime(DateUtil.date());
                    microgridCareRecordEntity.setUpdateBy(currentUser.getId());
                    microgridCareRecordEntity.setUpdateTime(DateUtil.date());
                    microgridCareRecordEntity.setCareObject(protractFlag);
                    microgridCareRecordService.save(microgridCareRecordEntity);
                }
            }
        }
    }

    /**
     * 调整边界
     *
     * @param request
     */
    @Transactional
    @Override
    public String adjustBoundary(PolygonRequest request) {
        log.debug("管理后台调整边界入参{}", request);
        LoginUser currentUser = SystemUtil.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CommonException("解析用户失败");
        }
        String type = request.getTypes().get(0);
        MicroStreetData streetData = microStreetDataService.getMicroStreetDataById(request.getId());

        MicroStreetData data = new MicroStreetData();
        data.setId(request.getId());
        data.setWkt(request.getWkt());
        data.setUpdateBy(currentUser.getId());
        data.setUpdateTime(DateUtil.date());
        microStreetDataService.updateWKT(data);


        if ((type.equals("沿街商铺") && Objects.equals(request.getProtractFlag(), ProtractEnum.DRAW.getCode()))
                || (Objects.equals(request.getProtractFlag(), ProtractEnum.ROAD.getCode() ) && type.equals("沿街商铺"))
        ) {//修改基础数据表并添加审核记录
            MicroStreetAuditLog record = MicroStreetAuditLog.builder()
                    .id(UUID.randomUUID().toString())
                    .streetId(request.getId())
                    .operationType(OperationTypeEnum.UPDATE.getCode())
                    .createBy(currentUser.getRealname())
                    .createPhone(currentUser.getPhone())
                    .createTime(new Date())
                    .createId(currentUser.getWorkNo())
                    .reviewState(ReviewEnum.REVIEWED.getCode())
                    .newWkt(request.getWkt())
                    .oldWkt(streetData.getWkt())
                    .microGridCode(request.getMicroGridCode())
                    .microGridName(request.getMicroGridName())
                    .build();
            QueryWrapper<MicroStreetAuditLog> wrapper = new QueryWrapper<>();
            wrapper.eq("street_id", request.getId());
            MicroStreetAuditLog one = microStreetAuditLogService.getOne(wrapper);
            if (Objects.nonNull(one)) {
                record.setReviewState(one.getReviewState());
                microStreetAuditLogService.updateByStreetId(record);
            } else {
                microStreetAuditLogService.addAuditLog(record);
            }
        }
        return "调整成功";
    }

    @Transactional
    @Override
    public String deleteBoundary(String id, String type, Integer protractFlag) {
        LoginUser currentUser = SystemUtil.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CommonException("查询用户信息失败");
        }
        //自己绘制的面是沿街的 需要审批
        if (type.equals("沿街商铺") && Objects.equals(protractFlag, ProtractEnum.DRAW.getCode())) {
            MicroStreetAuditLog record = MicroStreetAuditLog.builder()
                    .id(UUID.randomUUID().toString())
                    .streetId(id)
                    .operationType(OperationTypeEnum.DELETE.getCode())
                    .createBy(currentUser.getRealname())
                    .createTime(new Date())
                    .createId(currentUser.getWorkNo())
                    .reviewState(ReviewEnum.REVIEWED.getCode())
                    .createPhone(currentUser.getPhone())
                    .build();
            QueryWrapper<MicroStreetAuditLog> wrapper = new QueryWrapper<>();
            wrapper.eq("street_id", id);
            MicroStreetAuditLog one = microStreetAuditLogService.getOne(wrapper);
            if (Objects.nonNull(one)) {
                record.setReviewState(one.getReviewState());
                microStreetAuditLogService.updateByStreetId(record);
            } else {
                microStreetAuditLogService.addAuditLog(record);
            }
            return "已经进入待审核流程!";
        } else if (protractFlag.equals(ProtractEnum.ROAD.getCode())) {//路网数据不允许删除
            return "该类型不允许删除!";
        } else {
            microStreetDataService.removeById(id);
            return "删除成功!";
        }
    }

    @Transactional
    @Override
    public Boolean copyBoundary(PolygonRequest request) {
        log.debug("管理后台添加边界入参{}", request);
        LoginUser currentUser = SystemUtil.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CommonException("查询用户信息失败");
        }
        List<String> types = request.getTypes();
        Integer protractFlag = request.getProtractFlag();
        boolean res = true;

        // 根据微网格查询网格、区县、地市编码
        int startLevel = 5; // 起始级别
        int endLevel = 2;   // 结束级别
        List<UniAddrRegion> ancestors = uniAddrRegionService.getAncestorsUpToLevel(request.getMicroGridCode(), startLevel, endLevel);

        if (CollectionUtils.isNotEmpty(types)) {
            if (protractFlag.equals(ProtractEnum.CIRCLE.getCode())) { // 不需要审核，直接保存
                //批量新增
                setRegionCodesAndNames(types, ancestors, request, currentUser);
            } else if (protractFlag.equals(ProtractEnum.DRAW.getCode()) || protractFlag.equals(ProtractEnum.ROAD.getCode())) {
                for (String type : types) {
                    MicroStreetData data = MicroStreetData.builder()
                            .id(UUID.randomUUID().toString())
                            .gridName(request.getGridName())
                            .gridCode(request.getGridCode())
                            .microGridCode(request.getMicroGridCode())
                            .microGridName(request.getMicroGridName())
                            .name(request.getName())
                            .wkt(request.getWkt())
                            .type(type)
                            .createTime(new Date())
                            .phone(currentUser.getPhone())
                            .createBy(currentUser.getUsername())
                            .workNo(currentUser.getWorkNo())
                            .protractFlag(protractFlag)
                            .build();
                    if (ancestors.size() > 0) {
                        UniAddrRegion microRegion = ancestors.get(0);
                        if (microRegion != null) {
                            data.setMicroGridCode(microRegion.getCode());
                            data.setMicroGridName(microRegion.getName());
                        }
                    }
                    if (ancestors.size() > 1) {
                        UniAddrRegion gridRegion = ancestors.get(1);
                        if (gridRegion != null) {
                            data.setGridCode(gridRegion.getCode());
                            data.setGridName(gridRegion.getName());
                        }
                    }
                    if (ancestors.size() > 2) {
                        UniAddrRegion disRegion = ancestors.get(2);
                        if (disRegion != null) {
                            data.setDisCode(disRegion.getCode());
                            data.setDisName(disRegion.getName());
                        }
                    }
                    if (ancestors.size() > 3) {
                        UniAddrRegion cityRegion = ancestors.get(3);
                        if (cityRegion != null) {
                            data.setCityCode(cityRegion.getCode());
                            data.setCityName(cityRegion.getName());
                        }
                    }
                    microStreetDataService.saveBoundary(data);
                    if (type.equals("沿街商铺")) {//是否需要审核
                        MicroStreetAuditLog record = MicroStreetAuditLog.builder()
                                .id(UUID.randomUUID().toString())
                                .streetId(data.getId())
                                .operationType(OperationTypeEnum.UPDATE.getCode())
                                .createBy(currentUser.getUsername())
                                .createPhone(currentUser.getPhone())
                                .createTime(new Date())
                                .createId(currentUser.getWorkNo())
                                .reviewState(ReviewEnum.REVIEWED.getCode())
                                .newWkt(request.getWkt())
                                .microGridCode(request.getMicroGridCode())
                                .microGridName(request.getMicroGridName())
                                .build();
                        microStreetAuditLogService.addAuditLog(record);
                    }
                }
            }
        }
        return res;
    }

    private void setRegionCodesAndNames(List<String> types, List<UniAddrRegion> ancestors, PolygonRequest request, LoginUser currentUser) {
        for (String type : types) {
            MicroStreetData data = MicroStreetData.builder()
                    .id(UUID.randomUUID().toString())
                    .gridName(request.getGridName())
                    .gridCode(request.getGridCode())
                    .microGridCode(request.getMicroGridCode())
                    .microGridName(request.getMicroGridName())
                    .name(request.getName())
                    .wkt(request.getWkt())
                    .type(type)
                    .createTime(new Date())
                    .phone(currentUser.getPhone())
                    .createBy(currentUser.getUsername())
                    .workNo(currentUser.getWorkNo())
                    .protractFlag(request.getProtractFlag())
                    .build();
            if (ancestors.size() > 0) {
                UniAddrRegion microRegion = ancestors.get(0);
                if (microRegion != null) {
                    data.setMicroGridCode(microRegion.getCode());
                    data.setMicroGridName(microRegion.getName());
                }
            }
            if (ancestors.size() > 1) {
                UniAddrRegion gridRegion = ancestors.get(1);
                if (gridRegion != null) {
                    data.setGridCode(gridRegion.getCode());
                    data.setGridName(gridRegion.getName());
                }
            }
            if (ancestors.size() > 2) {
                UniAddrRegion disRegion = ancestors.get(2);
                if (disRegion != null) {
                    data.setDisCode(disRegion.getCode());
                    data.setDisName(disRegion.getName());
                }
            }
            if (ancestors.size() > 3) {
                UniAddrRegion cityRegion = ancestors.get(3);
                if (cityRegion != null) {
                    data.setCityCode(cityRegion.getCode());
                    data.setCityName(cityRegion.getName());
                }
            }
            microStreetDataService.saveBoundary(data);
        }
    }

    @Override
    public List<DataResponse> selectRepeatPolygonData(RepeatPolygonRequest request) {
        log.debug("查询重复面列表入参{}",request);
        return microStreetDataService.selectRepeatDataList(request);
    }
}
